import { updatePassword, updateUser, uploadAvatar } from '@/services/system/user';
import { UploadOutlined } from '@ant-design/icons';
import ProForm, { ProFormFieldSet, ProFormText } from '@ant-design/pro-form';
import { Button, Form, Input, message, Modal, Upload } from 'antd';

import { LoadingOutlined, PlusOutlined } from '@ant-design/icons';
import type { UploadChangeParam } from 'antd/es/upload';
import type { RcFile, UploadFile, UploadProps } from 'antd/es/upload/interface';
import React, { Fragment, useState } from 'react';
import { useModel } from 'umi';
import styles from './BaseView.less';
const getBase64 = (img: RcFile, callback: (url: string) => void) => {
  const reader = new FileReader();
  reader.addEventListener('load', () => callback(reader.result as string));
  reader.readAsDataURL(img);
};

const beforeUpload = (file: RcFile) => {
  const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
  if (!isJpgOrPng) {
    message.error('You can only upload JPG/PNG file!');
  }
  const isLt2M = file.size / 1024 / 1024 < 2;
  if (!isLt2M) {
    message.error('Image must smaller than 2MB!');
  }
  return isJpgOrPng && isLt2M;
};
const validatorPhone = (rule: any, value: string[], callback: (message?: string) => void) => {
  // if (!value[0]) {
  //   callback('Please input your area code!');
  // }
  if (!value[0]) {
    callback('Please input your phone number!');
  }
  callback();
};
let userId = "'";
// 头像组件 方便以后独立，增加裁剪之类的功能
const AvatarView = ({ avatar }: { avatar: string }) => (
  <>
    <div className={styles.avatar_title}>头像</div>
    <div className={styles.avatar}>
      <img src={avatar} alt="avatar" />
    </div>
    <Upload
      showUploadList={false}
      action={async (value: RcFile) => {
        const formData = new FormData();
        formData.append('file', value);
        formData.append('userId', userId);
        await uploadAvatar(formData);
        console.log(value);
      }}
    >
      <div className={styles.button_view}>
        <Button>
          <UploadOutlined />
          更换头像
        </Button>
      </div>
    </Upload>
  </>
);

const BaseView: React.FC = () => {
  const { initialState, setInitialState } = useModel('@@initialState');

  const { currentUser } = initialState;
  const [formVisit, setFormVisit] = useState(false); // 新建和编辑提示框
  const [formTitle, setFormTitle] = useState('重置密码'); // 标题
  const [confirmLoading3, setConfirmLoading3] = useState(false); //加载
  const [form2] = Form.useForm();
  userId = currentUser.id;
  const getAvatarURL = () => {
    console.log('---');
    if (currentUser) {
      if (currentUser.avatarPath) {
        return currentUser.avatarPath;
      }
      const url = 'http://gw.alipayobjects.com/zos/rmsportal/BiazfanxmamNRoxxVxka.png';
      return url;
    }
    return '';
  };

  const handleFinish = async (values: Record<string, any>) => {
    //
    console.log(values);
    await updateUser({ id: currentUser.id, email: values.email, phone: values.phone[0] });
    message.success('更新基本信息成功');
  };
  const handleSubmit2 = async () => {
    console.log(form2.getFieldsValue(), '----form2.getFieldsValue()----');
    setConfirmLoading3(true);

    await updatePassword({ ...form2.getFieldsValue(), id: currentUser.id });
    setConfirmLoading3(false);
    setFormVisit(false);
    // 这个爆红不用管(从新加载页面)
    // actionRef.current.reload();
  };
  const [loading, setLoading] = useState(false);
  const [imageUrl, setImageUrl] = useState<string>(currentUser.avatarPath);

  const handleChange: UploadProps['onChange'] = (info: UploadChangeParam<UploadFile>) => {
    if (info.file.status === 'uploading') {
      setLoading(true);
      return;
    }
    if (info.file.status === 'done') {
      // Get this url from response in real world.
      getBase64(info.file.originFileObj as RcFile, (url) => {
        setLoading(false);
        setImageUrl(url);
      });
    }
  };

  const uploadButton = (
    <div>
      {loading ? <LoadingOutlined /> : <PlusOutlined />}
      <div style={{ marginTop: 8 }}>Upload</div>
    </div>
  );

  return (
    <Fragment>
      <div className={styles.baseView}>
        <>
          <div className={styles.left}>
            <ProForm
              layout="vertical"
              onFinish={handleFinish}
              submitter={{
                searchConfig: {
                  submitText: '更新基本信息',
                },
                render: (_, doms) => {
                  return [
                    doms[1],
                    <Button
                      htmlType="button"
                      onClick={() => {
                        setFormVisit(true);
                      }}
                      key="read"
                    >
                      修改密码
                    </Button>,
                  ];
                },
              }}
              initialValues={{
                ...currentUser,
                phone: currentUser?.phone?.split('-'),
              }}
              hideRequiredMark
            >
              <ProFormText
                width="md"
                name="email"
                label="邮箱"
                rules={[
                  {
                    required: true,
                    message: '请输入您的邮箱!',
                  },
                ]}
              />
              <ProFormText
                width="md"
                name="name"
                label="名称"
                rules={[
                  {
                    required: true,
                    message: '请输入您的昵称!',
                  },
                ]}
              />

              <ProFormFieldSet
                name="phone"
                label="联系电话"
                rules={[
                  {
                    required: true,
                    message: '请输入您的联系电话!',
                  },
                  { validator: validatorPhone },
                ]}
              >
                {/* <Input className={styles.area_code} /> */}
                <Input className={styles.phone_number} />
              </ProFormFieldSet>
            </ProForm>
          </div>
          <div className={styles.right}>
            <div className={styles.avatar_title}>头像</div>
            <div className={styles.avatar}>
              <img src={imageUrl} alt="avatar" />
            </div>
            <Upload
              showUploadList={false}
              action={async (value: RcFile) => {
                const formData = new FormData();
                formData.append('file', value);
                formData.append('userId', userId);
                const result = await uploadAvatar(formData);
                setImageUrl(result.data);
              }}
              beforeUpload={beforeUpload}
              onChange={handleChange}
            >
              <div className={styles.button_view}>
                <Button>
                  <UploadOutlined />
                  更换头像
                </Button>
              </div>
            </Upload>
            {/* <AvatarView avatar={getAvatarURL()} /> */}
          </div>

          <Modal
            title={formTitle}
            visible={formVisit}
            onOk={handleSubmit2}
            confirmLoading={confirmLoading3}
            onCancel={() => {
              setFormVisit(false);
            }}
          >
            <Form
              name="wrap"
              labelCol={{ flex: '110px' }}
              labelAlign="left"
              labelWrap
              form={form2}
              wrapperCol={{ flex: 1 }}
              colon={false}
            >
              {/* <Form.Item label="id" name="id" hidden={true}>
                <Input />
              </Form.Item> */}

              <Form.Item
                label="密码"
                name="password"
                rules={[{ required: true, message: 'Please input your password!' }]}
              >
                <Input.Password />
              </Form.Item>
            </Form>
          </Modal>
        </>
      </div>
    </Fragment>
  );
};

export default BaseView;
